package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.util.IdSequence;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author liuyp
 * @date 2021/02/02
 */
@Service
public class VideoApiImpl implements VideoApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdSequence idSequence;

    @Override
    public String save(Video video) {
        video.setId(ObjectId.get());
        video.setVid(idSequence.getNextId("video"));
        video.setCreated(System.currentTimeMillis());

        mongoTemplate.save(video);
        return video.getId().toHexString();
    }

    @Override
    public PageResult<Video> findVideoList(int page, int pagesize) {
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page - 1, pagesize));

        List<Video> videoList = mongoTemplate.find(query, Video.class);
        long count = mongoTemplate.count(query, Video.class);
        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult<>((int)count, pagesize, pages, page, videoList);
    }

    @Override
    public PageResult<Video> findVideoListByUid(int page, int pagesize, Long uid) {
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page-1, pagesize));

        if (uid != null) {
            query.addCriteria(Criteria.where("userId").is(uid));
        }

        List<Video> videoList = mongoTemplate.find(query, Video.class);
        long count = mongoTemplate.count(query, Video.class);

        int pages = (int) Math.ceil(count * 1.0 / pagesize);

        return new PageResult<>((int) count, pagesize, pages, page, videoList);
    }

    @Override
    public Video findById(String videoId) {
        return mongoTemplate.findById(new ObjectId(videoId), Video.class);
    }

    @Override
    public List<Video> findVideoByVids(List<Long> vidList) {
        Query query = new Query(Criteria.where("vid").in(vidList));
        return mongoTemplate.find(query, Video.class);
    }
}
